package com.breeze.components.web.config;

import cn.hutool.core.util.StrUtil;
import com.breeze.components.web.config.properties.XssProperties;
import com.breeze.components.web.filter.RepeatableFilter;
import com.breeze.components.web.filter.XssFilter;
import jakarta.servlet.DispatcherType;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Filter配置
 *
 * @author breze
 */
@AutoConfiguration
@EnableConfigurationProperties(XssProperties.class)
public class FilterConfig {

  @SuppressWarnings({"rawtypes", "unchecked"})
  @Bean
  @ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
  public FilterRegistrationBean xssFilterRegistration(XssProperties xssProperties) {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setDispatcherTypes(DispatcherType.REQUEST);
    registration.setFilter(new XssFilter());
    if (StrUtil.isNotEmpty(xssProperties.getUrlPatterns())) {
      registration.addUrlPatterns(
          StrUtil.splitToArray(xssProperties.getUrlPatterns(), StrUtil.COMMA));
    }
    registration.setName("xssFilter");
    registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
    Map<String, String> initParameters = new HashMap<>();
    if (StrUtil.isNotEmpty(xssProperties.getExcludes())) {
      initParameters.put("excludes", xssProperties.getExcludes());
    }
    registration.setInitParameters(initParameters);
    return registration;
  }

  @SuppressWarnings({"rawtypes", "unchecked"})
  @Bean
  public FilterRegistrationBean someFilterRegistration() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new RepeatableFilter());
    registration.addUrlPatterns("/*");
    registration.setName("repeatableFilter");
    registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
    return registration;
  }

  /** 跨域配置 */
  @Bean
  public CorsFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    // 设置访问源地址
    config.addAllowedOriginPattern("*");
    // 设置访问源请求头
    config.addAllowedHeader("*");
    // 设置访问源请求方法
    config.addAllowedMethod("*");
    // 有效期 1800秒
    config.setMaxAge(1800L);
    // 添加映射路径，拦截一切请求
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    // 返回新的CorsFilter
    return new CorsFilter(source);
  }
}
